package tjx.Listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

//@WebListener()
public class GetConnListener implements ServletContextListener{
    public GetConnListener() {
    }
    public void contextInitialized(ServletContextEvent sce) {
        try {  //给application添加属性number
        ServletContext application=sce.getServletContext();
        application.setAttribute("number",0);
        String driver=application.getInitParameter("driver");
        String url=application.getInitParameter("url");
        String user=application.getInitParameter("user");
        String pass=application.getInitParameter("pass");

        Class.forName(driver);
        Connection conn= DriverManager.getConnection(url,user,pass);
        application.setAttribute("conn",conn);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Listener中获取连接数据库出现异常"+e.getMessage());
            e.printStackTrace();
        }

    }

    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext aapplication = sce.getServletContext();
        Connection conn = (Connection) aapplication.getAttribute("conn");
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
